

import time, copy

from scripts.utils import input_reading, constants
from dexen.libs import dexen_api, constants as dc

""" GLOBALS """
script_api = dexen_api.getScriptApi()
INF = 1000000000
boxes = input_reading.read_input()
n_boxes = len(boxes)

best_individual = {
    "area":INF
}
file_id = 0
iter = 0

def is_best(individual):
    global best_individual
    if (individual['area'] < best_individual['area']):
        best_individual = copy.deepcopy(individual)

def evaluate_individual_width(individual):
    phenotype = individual['phenotype']
    orient = individual['orient']
    max_found = 0
    side = 0
    for i in range(n_boxes):
        if orient[i] == 0:
            side = boxes[i]['w']
        else:
            side = boxes[i]['h']
        if phenotype[i]['x'] + side > max_found:
            max_found = phenotype[i]['x'] + side
    individual['min_width'] = float(max_found)
    
def evaluate_width(population):
    for individual in population:
        evaluate_individual_width(individual)

def evaluate_individual_height(individual):
    phenotype = individual['phenotype']
    orient = individual['orient']
    max_found = 0
    side = 0
    for i in range(n_boxes):
        if orient[i] == 0:
            side = boxes[i]['h']
        else:
            side = boxes[i]['w']
        if phenotype[i]['y'] + side > max_found:
            max_found = phenotype[i]['y'] + side
    individual['min_height'] = float(max_found)
                
def evaluate_height(population):
    for individual in population:
        evaluate_individual_height(individual)

cur_time = time.time()

def evaluate(): 
    population = script_api.downloadIndividuals(
        select = ("phenotype", "orient"), 
        where = (
            ("state", dc.EQUAL, constants.ALIVE),
            ("phenotype", dc.NOT_EQUAL, None),
            ("min_width", dc.EQUAL, None),
            ("min_height", dc.EQUAL, None),
            ("area", dc.EQUAL, None)
        ), 
        count = constants.EVALUATION_SIZE
    )    
    
    global file_id, iter, cur_time
    iter += 1
    file_id += 1
    #print "I am in evaluate"       
    
    evaluate_width(population)
    evaluate_height(population)
    for individual in population:
        individual['area'] = individual['min_width'] * individual['min_height']
        is_best(individual)
        
    #print "At iter:", iter, "The best individual: ", best_individual
    
    #print "Evaluation takes", time.time() - cur_time, "seconds."

    cur_time = time.time()    
    script_api.uploadIndividuals(population)
    